<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h2>Promise封装数据请求</h2>
</body>
<script>
    //基于Promise封装JS原生数据请求函数
    function Ajax(options) {
     return new Promise((resolve,reject)=>{

        //console.log('options:',options)
        let xhr=null;
        if(window.XMLHttpRequest) {
            xhr=new XMLHttpRequest()
        }else {
            //IE
            xhr=new ActiveXObject()
        }

      
        let  dataStr='';
        if(options.method==='GET') {
            //对data参数处理
            Object.entries(options.data).forEach(([key,value])=>{
         
            dataStr+=`${key}=${value}&`
            })
            //创建连接
           // xhr.open(请求方式，请求地址，是否同异步)
           xhr.open(options.method,options.url+`?${dataStr}`,true)
           xhr.send()
        }

        if(options.method==='POST') {
            //初始化
            xhr.open(options.method,options.url,true)
            //设置请求头
            xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
            //发送请求
            xhr.send(JSON.stringify(options.data))

        }

        //监听是否数据返回
        xhr.onreadystatechange=function() {
            if(xhr.readyState===4) {
                if(xhr.status>=200 && xhr.status<300) {
                    
                  //  options.success(JSON.parse(xhr.responseText))
                    resolve(JSON.parse(xhr.responseText))
                }else {
                    reject('数据请求错误')
                }
            }
        }
        })

    }

    Ajax({
        url:'https://www.lexuemiao.com/api/app/home/getFirstClassify',
        method:'GET',
        data:{id:1001,name:'jack'},
        //header:{},
        // success(res) {
        //     //渲染操作
        //     console.log('拿到结果:',res)
        // }
    }).then(res=>{
        console.log('拿到结果then:',res)
    }).catch(err=>{
        console.log('拿到结果catch:',err)
    })


    Promise.all([ Ajax({
        url:'https://www.lexuemiao.com/api/app/home/getFirstClassify',
        method:'GET',
        data:{id:1001,name:'jack'},
       
    }), Ajax({
        url:'https://www.lexuemiao.com/api/app/webConfig',
        method:'GET',
        data:{},
       
    })]).then(res=>{
        console.log('race---promise返回的结果：',res)
    }).catch(error=>{
        console.log(error)
    })
</script>
</html>